package com.api.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.api.apicommon.response.BaseResponse;
import com.api.apicommon.response.ErrorCode;
import com.api.apicommon.response.ResultUtils;
import com.api.pay.mapper.ApiOrderMapper;
import com.api.pay.model.domain.ApiGoods;
import com.api.pay.model.domain.ApiOrder;
import com.api.pay.model.dto.order.OrderDto;
import com.api.pay.service.ApiGoodsService;
import com.api.pay.service.ApiOrderService;
import com.api.pay.util.AliPayUtil;
import com.api.pay.util.PayConstant;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import static com.api.pay.config.RabbitConfiguration.API_PAY_EXCHANGE_NAME;

/**
 * @author Administrator
 * @description 针对表【api-order】的数据库操作Service实现
 * @createDate 2024-06-22 14:42:17
 */
@Slf4j
@Service
public class ApiOrderServiceImpl extends ServiceImpl<ApiOrderMapper, ApiOrder>
        implements ApiOrderService {
    @Autowired
    AliPayUtil aliPayUtil;
    @Autowired
    ApiGoodsService apiGoodsService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     * 查询订单
     *
     * @param userId
     * @return
     */
    @Override
    public BaseResponse queryOrderById(Long userId) {
        QueryWrapper<ApiOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .orderBy(true, true, "createTime");
        List<ApiOrder> list = list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(list);
    }

    /**
     * 下单
     *
     * @param orderDto
     * @param userId
     * @return
     * @throws AlipayApiException
     */
    @Override
    public BaseResponse order(OrderDto orderDto, Long userId) throws AlipayApiException {
        //创建订单
        ApiOrder apiOrder = createOrder(orderDto, userId);
        //存到数据库中 生成对应的支付二维码
        String shareCode = aliPayUtil.createTransaction(apiOrder);
        if (shareCode == null) {
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR);
        }
        apiOrder.setQrCode(shareCode);
        //发送到消息队列(死信队列)
        boolean isSuccess = sendRabbitMqMessage(apiOrder);
        if (!isSuccess) {
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR);
        }
        //保存到数据库
        save(apiOrder);
        return ResultUtils.success(apiOrder);
    }

    /**
     * 访问支付宝接口,查看订单状态
     *
     * @param order
     * @return
     */
    @Override
    public String queryOrderStatus(ApiOrder order) {
        AlipayTradeQueryResponse alipayTradeQueryResponse;
        try {
             alipayTradeQueryResponse = aliPayUtil.queryOrder(order);
        } catch (AlipayApiException e) {
           return e.getErrMsg();
        }
        return alipayTradeQueryResponse.getTradeStatus();
    }

    private boolean sendRabbitMqMessage(ApiOrder apiOrder) {
        try {
            MessageProperties messageProperties = new MessageProperties();
            MessageConverter converter = rabbitTemplate.getMessageConverter();
            Message orderMessage = converter.toMessage(apiOrder, messageProperties);
            rabbitTemplate.send(API_PAY_EXCHANGE_NAME, "order", orderMessage);
        } catch (AmqpException amqpException) {
            log.error("消息发送失败", amqpException);
            if (!sendRabbitMqMessage(apiOrder)) {
                return false;
            }
        }
        return true;
    }

    @NotNull
    private ApiOrder createOrder(OrderDto orderDto, Long userId) {
        ApiOrder apiOrder = new ApiOrder();
        BeanUtil.copyProperties(orderDto, apiOrder);
        apiOrder.setStatus(PayConstant.TRADE_NO_PAY);
        String timestamp = String.valueOf(System.currentTimeMillis());
        int[] randomInts = RandomUtil.randomInts(5);
        String replace = Arrays.toString(randomInts).replace("[", "").replace("]", "")
                .replace(",", "").replace(" ", "");
        String orderSn = timestamp + replace;
        //订单编号=时间戳+5位随机数
        apiOrder.setOrderSn(orderSn);
        QueryWrapper<ApiGoods> apiGoodsQueryWrapper = new QueryWrapper<>();
        apiGoodsQueryWrapper.eq("id", orderDto.getGoodsId());
        ApiGoods apiGoods = apiGoodsService.getOne(apiGoodsQueryWrapper);
        apiOrder.setSubject(apiGoods.getProductName());
        apiOrder.setUserId(userId);
        BigDecimal price = apiGoods.getPrice();
        apiOrder.setTotalAmount(price.multiply(new BigDecimal(orderDto.getCount())));
        apiOrder.setPrice(price);
        //设置流水号
        stringRedisTemplate.opsForValue().setIfAbsent(apiOrder.getOrderSn(), "0");
        apiOrder.setSerialNumber(apiOrder.getOrderSn() + "_" + stringRedisTemplate.opsForValue().get(apiOrder.getOrderSn()));
        return apiOrder;
    }


}




